@page "/database-connection/select-tables/{Id}"
@using Text2Sql.Net.Repositories.Text2Sql.DatabaseSchema
@using Text2Sql.Net.Repositories.Text2Sql.DatabaseConnection
@using Text2Sql.Net.Domain.Interface
@inject IDatabaseConnectionConfigRepository DatabaseConnectionConfigRepository
@inject ISchemaTrainingService SchemaTrainingService
@inject MessageService MessageService
@inject NavigationManager NavigationManager

<PageContainer Title="@($"选择表训练")">
    <Extra>
        <Space>        
            <SpaceItem>
                <Button Type="@ButtonType.Default" OnClick="@NavigateToDetails">
                    <Icon Type="@IconType.Outline.ArrowLeft" />
                    返回
                </Button>
            </SpaceItem>
        </Space>
    </Extra>

    <ChildContent>
        <Card>     
            @if (_model != null)
            {
                <Descriptions Bordered>
                    <DescriptionsItem Title="数据库类型" Span="1">
                         @_model.Name
                    </DescriptionsItem>
                    <DescriptionsItem Title="数据库类型" Span="2">
                        @_model.DbType
                    </DescriptionsItem>
                    <DescriptionsItem Title="连接字符串" Span="2">
                        @_model.ConnectionString
                    </DescriptionsItem>
                </Descriptions>
            }
            <Alert Type="@AlertType.Info" Description="请选择您想要训练的表，训练完成后这些表的Schema信息将被添加到向量数据库中。" ShowIcon="true" />
        </Card>
        <div Class="flex-container">
            <div class="flex-item">    
                @if (_model != null)
                {
                    <div style="margin-bottom: 16px;">
                        <div style="display: flex; gap: 16px; align-items: center;">
                            <div style="flex: 1;">
                                <Input Placeholder="搜索表名或描述..." @bind-Value="_searchKeyword" @oninput="OnSearchChanged" AllowClear="true" />
                            </div>
                            <div>
                                <Space>
                                    <SpaceItem>
                                        <Checkbox CheckedChanged="OnSelectAllChanged">全选</Checkbox>
                                    </SpaceItem>
                                    <SpaceItem>
                                        <Button Type="@ButtonType.Primary" Loading="@_loadingTables" OnClick="LoadTables">
                                          <Icon Type="@IconType.Outline.Cloud" /> 刷新
                                        </Button>
                                    </SpaceItem>  
                                </Space>
                            </div>
                        </div>
                    </div>

                    @if (_filteredTables.Any())
                    {
                        <div style="border: 1px solid #d9d9d9; border-radius: 8px; padding: 16px; max-height: 78vh; overflow-y: auto;">
                            @foreach (var table in _filteredTables)
                            {
                                <div style="margin-bottom: 8px; padding: 8px; border: 1px solid #f0f0f0; border-radius: 4px;">
                                    <Checkbox Checked="_trainedTables.Select(a=>a.TableName).Contains(table.TableName)" OnChange="@((bool isChecked) => OnTableSelectionChanged(table.TableName, isChecked))">
                                        <div>
                                            <strong>@table.TableName</strong>
                                            @if (!string.IsNullOrEmpty(table.Description))
                                            {
                                                <br />
                                                <span style="color: #666; font-size: 12px;">@table.Description</span>
                                            }
                                        </div>
                                    </Checkbox>
                                </div>
                            }
                        </div>

                        @if (!string.IsNullOrWhiteSpace(_searchKeyword) && _filteredTables.Count != _tables.Count)
                        {
                            <div style="margin-top: 8px; color: #666; font-size: 14px;">
                                找到 @_filteredTables.Count 个表（共 @_tables.Count 个表）
                            </div>
                        }                 
                    }
                    else if (!_loadingTables)
                    {
                        <div style="text-align: center; padding: 40px; color: #999;">
                            @if (!string.IsNullOrWhiteSpace(_searchKeyword))
                            {
                                <div>未找到匹配的表</div>
                                <div style="font-size: 12px; margin-top: 8px;">请尝试修改搜索关键词</div>
                            }
                            else
                            {
                                <div>暂无数据表</div>
                            }
                        </div>
                    }
                }     
            </div>
            <div class="flex-item">
                <div style="display: flex; gap: 16px; align-items: center;">
                    <div style="flex: 1;">
                        <Alert Type="@AlertType.Warning" Message="@($"已选择： {_trainedTables.Count} 个表")" ShowIcon="true" />
                    </div>
                    <div>
                        <Space>
                            <SpaceItem>
                                <Button Type="@ButtonType.Primary"  Loading="@_trainingLoading" OnClick="TrainSelectedTables" Disabled="@(!_trainedTables.Any())">
                                训练选中的表 (@_trainedTables.Count())
                                </Button>
                            </SpaceItem>   
                            <SpaceItem>
                            <Button Type="@ButtonType.Link" OnClick="ClearSelectALL" Disabled="@(!_trainedTables.Any())">
                                 <Icon Type="@IconType.Outline.DeleteRow" />
                                    清空已选
                                </Button>
                            </SpaceItem>                                 
                        </Space>
                    </div>
                </div>
                @if (_trainedTables?.Any() == true)
                {
                    <Table TItem="TableInfo"
                           DataSource="@_trainedTables"
                           Bordered="true"
                           Size="@TableSize.Default"   
                           PageSize="10"
                           Responsive="true">
                        <AntDesign.Column TData="string" DataIndex="@nameof(TableInfo.TableName)" Title="表名">
                            <Text Strong>@context.TableName</Text>
                            <br />
                            <Text>@context.Description</Text>
                        </AntDesign.Column>
                        <AntDesign.Column TData="int" Title="列数" Width="60" Align="@ColumnAlign.Center">
                            <Tag Color="blue">@context.Columns.Count</Tag>
                        </AntDesign.Column>

                        <ActionColumn Title="操作" Width="80">
                            <Space>
                                <SpaceItem>
                                    <Button Type="@ButtonType.Link" Size="@ButtonSize.Small" 
                                      OnClick="@(() => RemoveSelect(context))" >
                                        <Icon Type="@IconType.Outline.Delete" />
                                        移除
                                    </Button>
                                </SpaceItem>
                            </Space>
                        </ActionColumn>
                    </Table>
                }
            </div>
        </div>
    </ChildContent>
</PageContainer>

<style>   
    .flex-container {
        display: flex; /* 启用 Flex 布局 */
        width: 100%; /* 确保容器宽度占满父级 */
        gap: 16px; /* 可选：设置子元素间距 */
    }

    /* 子元素样式 */
    .flex-item {
        flex: 1; /* 子元素平分可用空间 */
        /* 可选：设置最小宽度避免内容过窄 */
        min-width: 0; /* 解决内容溢出问题（如长文本） */
    }
</style>

@code {

    [Parameter]
    public string Id { get; set; } = string.Empty;

    private DatabaseConnectionConfig? _model = null;
    private List<TableInfo> _tables = new();
    private List<TableInfo> _filteredTables = new();

    private List<TableInfo> _trainedTables = new();

    private string _searchKeyword = string.Empty;
 
    private bool _loading = false;
    private bool _loadingTables = false;
    private bool _trainingLoading = false;

    protected override async Task OnInitializedAsync()
    {
        await LoadData();
        await LoadTables();
    }

    private async Task LoadData()
    {
        _loading = true;
        try
        {
            var data = await DatabaseConnectionConfigRepository.GetByIdAsync(Id);
            if (data != null)
            {
                _model = data;
            }
            else
            {
                _ = MessageService.Error("找不到指定的数据库连接配置");
                NavigateToDetails();
            }
        }
        catch (Exception ex)
        {
            _ = MessageService.Error($"加载数据失败: {ex.Message}");
            NavigateToDetails();
        }
        finally
        {
            _loading = false;
            StateHasChanged();
        }
    }

    private async Task LoadTables()
    {
        _loadingTables = true;
        try
        {
            _tables = await SchemaTrainingService.GetDatabaseTablesAsync(Id);

            _trainedTables = await SchemaTrainingService.GetTrainedTablesAsync(Id);        

            ApplySearch();
            StateHasChanged();
        }
        catch (Exception ex)
        {
            _ = MessageService.Error($"加载表列表失败: {ex.Message}");
        }
        finally
        {
            _loadingTables = false;
            StateHasChanged();
        }
    }

    private void OnSelectAllChanged(bool isChecked)
    {     
        if (isChecked)
        {
            _filteredTables.ForEach((table) =>
            {
                 if (_trainedTables.All(t => t.TableName != table.TableName)) { _trainedTables.Add(table);  }
            });
   
           // _selectedTables = _filteredTables.Select(t => t.TableName).ToList();
        }
      
        StateHasChanged();
    }

    private void OnTableSelectionChanged(string tableName, bool isChecked)
    {
        if (string.IsNullOrEmpty(tableName)) return;

        var table = _tables.FirstOrDefault(t => t.TableName == tableName);
        if (table == null) return;


        if (isChecked)
        {    
            if (_trainedTables.All(t => t.TableName != table.TableName)) { _trainedTables.Add(table);  }
        }
        else
        {
            var tbname = _trainedTables.FirstOrDefault(a => a.TableName == tableName);
            if (tbname != null)
            {
                _trainedTables.Remove(tbname);
            }
        }

        StateHasChanged();
    }

    private async Task TrainSelectedTables()
    {
        if (!_trainedTables.Any())
        {
            _ = MessageService.Warning("请选择要训练的表");
            return;
        }

        _trainingLoading = true;
        try
        {
            // 创建副本避免并发修改
            var selectedTableNames = _trainedTables.Select(a=>a.TableName).ToList();

            // 参数验证
            var validTableNames = selectedTableNames.Where(name => !string.IsNullOrWhiteSpace(name)).ToList();
            if (!validTableNames.Any())
            {
                _ = MessageService.Warning("没有有效的表名可以训练");
                return;
            }

            var result = await SchemaTrainingService.TrainDatabaseSchemaAsync(Id, validTableNames);

            if (result)
            {
                _ = MessageService.Success($"成功训练 {validTableNames.Count} 个表的Schema信息");
                NavigateToDetails();
            }
            else
            {
                _ = MessageService.Error("Schema训练失败");
            }
        }
        catch (Exception ex)
        {
            _ = MessageService.Error($"训练失败: {ex.Message}");
        }
        finally
        {
            _trainingLoading = false;
            StateHasChanged();
        }
    }

    private void NavigateToDetails()
    {
        NavigationManager.NavigateTo($"/database-connection/details/{Id}");
    }

    private void OnSearchChanged(ChangeEventArgs e)
    {
        _searchKeyword = e.Value?.ToString() ?? string.Empty;
        ApplySearch();
        StateHasChanged();
    }

    private void ApplySearch()
    {
        if (string.IsNullOrWhiteSpace(_searchKeyword))
        {
            _filteredTables = _tables.ToList();
        }
        else
        {
            var keyword = _searchKeyword.ToLowerInvariant();
            _filteredTables = _tables.Where(t =>
                t.TableName.ToLowerInvariant().Contains(keyword) ||
                (!string.IsNullOrEmpty(t.Description) && t.Description.ToLowerInvariant().Contains(keyword))
            ).ToList();
        }
    }

 

    /// <summary>
    /// 移除已选择的表
    /// </summary>
    /// <param name="table"></param>
    private void RemoveSelect(TableInfo table)
    {
        if (_trainedTables.Contains(table))
        {
            _trainedTables.Remove(table);
        }
    
        StateHasChanged();
    }

    private void ClearSelectALL()
    {
        _trainedTables.Clear();
    }
}
